package integration;

import misc.Function;
import utils.math.Configuration;

/*
 * i think that what we should have done. 
 * i took this algorithm from lect 10 2010, that was at the last page.
 * there is one thing that i am not sure about him and that is r_n i think you might can get in from Netali's maraton. 
 * 
 */
/*
 * 
 */
public class AdaptiveIntegration {
    
    
    public static double[] calculatAdaptiveIntergration(Function f, double a, double b, double tol){
	return calculatAdaptiveIntergration(f, a, b, tol, 0);
    }
    

    /**
     * 
     * @param f - function
     * @param a - start point
     * @param b - end poit
     * @param tol - computation tolerance
     * @param recursionCounter - recursion protector
     * @return
     */
    private static double[] calculatAdaptiveIntergration(Function f, double a, double b, double tol, int recursionCounter) {
	
	double[] result = new double[3];//{ 0, 0, 0};
	double tI1 = utils.math.MathCodes.calculateIntegralBR(f, a, b, 1);
	double tI2 = utils.math.MathCodes.calculateIntegralBR(f, a, b, 2);
	double richardsonError = (tI2 - tI1) / (Math.pow(2, 6) - 1);
	if (Math.abs(richardsonError) <= tol | recursionCounter == Configuration.MAX_RECURSION_TRIES) {
	    result[0] = tI2;
	    System.out.println(tI2);
	    result[1] = 2.0;
	    result[2] =  richardsonError;
	    return result;
	} else {
	    double midPoint = (a + b) / 2.0; 
	    double[] tLeftRecursion = calculatAdaptiveIntergration(f, a, midPoint, tol / 2.0, recursionCounter + 1);
	    double[] tRightRecursion = calculatAdaptiveIntergration(f, midPoint, b, tol / 2.0, recursionCounter + 1);
	    //Integral result
	    result[0] = tLeftRecursion[0] + tRightRecursion[0]; 
	    //Panels Count
	    result[1] = tLeftRecursion[1] + tRightRecursion[1];
	    //Total error
	    result[2] = tLeftRecursion[2] + tRightRecursion[2];
	    return result;
	}
    }
}
